package com.appbee.songs.client.ui;

import javax.inject.Inject;

import com.appbee.core.client.design.celltable.CellTableResources;
import com.appbee.core.client.ui.ISimpleFilterView;
import com.appbee.lyrdb.client.presenter.LyricDataProvider;
import com.appbee.lyrdb.client.text.LyrStrings;
import com.appbee.lyrdb.client.ui.LyrSongTable;
import com.appbee.lyrdb.shared.LyrSongProxy;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.Range;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;

public class LyrSongSearchPopup extends Composite implements ISimpleFilterView
{

	private static LyrSongSearchPopupUiBinder uiBinder = GWT
			.create(LyrSongSearchPopupUiBinder.class);

	interface LyrSongSearchPopupUiBinder extends
			UiBinder<Widget, LyrSongSearchPopup>
	{
	}
	@UiField
	TextBox searchBox;

	@UiField(provided=true)
	LyrSongTable cellTable;
	
	private final PopupPanel popupPanel = new PopupPanel();

	@Inject
	public LyrSongSearchPopup(	final LyricDataProvider dataProvider,
								CellTableResources res,
								LyrStrings lyrStrings)
	{
		cellTable = new LyrSongTable(10, res, lyrStrings);
		
		popupPanel.setAutoHideEnabled(true);
		popupPanel.setAnimationEnabled(true);
		
		initWidget(uiBinder.createAndBindUi(this));

		dataProvider.setFilterView(this);
		dataProvider.addDataDisplay(cellTable.getHasData());
		popupPanel.setWidget(this);
		searchBox.addKeyDownHandler(new KeyDownHandler()
		{
			
			@Override
			public void onKeyDown(KeyDownEvent event)
			{
				if(event.getNativeKeyCode()==KeyCodes.KEY_ENTER)
				{
					dataProvider.onSearch();
				}
			}
		});
	}
	
	public void showRelativeTo(UIObject target)
	{
		popupPanel.showRelativeTo(target);
		searchBox.setFocus(true);
	}
	
	public void addSelectionChangeHandler(Handler handler)
	{
		cellTable.addSelectionChangeHandler(handler);
	}
	
	public LyrSongProxy getSelectedSong()
	{
		return cellTable.getSelectedSong();
	}

	@Override
	public String getSearchValue()
	{
		return searchBox.getValue();
	}

	public void clearData()
	{
		searchBox.setValue("");
		cellTable.getHasData().setVisibleRangeAndClearData(	new Range(0, 10),
				false);
	}
	
}
